package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.entity.Comment;
import org.clipjoint.entity.Game;
import org.clipjoint.entity.KeyWord;
import org.clipjoint.entity.User;
import org.clipjoint.entity.dto.GameDto;
import org.clipjoint.enums.GameTypeEnum;
import org.clipjoint.service.CommentAdminService;
import org.clipjoint.service.GameShopService;
import org.clipjoint.service.impl.CommentAdminServiceImpl;
import org.clipjoint.service.impl.GameShopServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/list")
public class GameShopController extends HttpServlet {
    private GameShopService gameService = new GameShopServiceImpl();
    private CommentAdminService commentService = new CommentAdminServiceImpl();

    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        switch (method){
            case "list":
                list(request, response);
                break;
            case "detail":
                detail(request, response);
                break;
            case "addDream":
                addDream(request, response);
                break;
            case "buy":
                buy(request, response);
            case "remove":
                remove(request, response);
                break;
                        
        }
    }

    private void remove(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("onlineUser");
        //判断用户是否登录
        if (user.getId() == 0){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).build()));
            return;
        }

        //获取游戏id
        Long gameid = Long.valueOf(request.getParameter("gameid"));
        //获取在线用户id
        Long id = user.getId();

        //移除愿望单
        gameService.remove(id,gameid);
    }

    //立即购买
    private void buy(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("onlineUser");
        //判断用户是否登录
        if (user == null){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).msg("您还未登录,请先登录").build()));
            return;
        }

        //获取游戏id
        Long gameid = Long.valueOf(request.getParameter("gameid"));
        //根据游戏id查游戏详情
        Game game = null;
        try {
            game = gameService.getone(gameid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //判断用户余额是否足够
        if(user.getAccount() <= game.getPrice()){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).msg("余额不足，购买失败").build()));
            return;
        }

        user.setAccount((long) (user.getAccount()-game.getPrice()));

        KeyWord keyWord = null;
        try {
           keyWord = gameService.getKey(gameid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if(keyWord == null){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(2).msg("该游戏暂无库存，敬请期待").build()));
            return;
        }

        //购买
        int result = 0;
        try {
            result = gameService.buy(user, game , keyWord.getKeyword());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(result == 1){
            try {
                gameService.delDream(user,game);
                gameService.updateKey(keyWord.getKeyword());
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(0).msg("购买成功").build()));
        }
    }

    //加入愿望单
    private void addDream(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("onlineUser");
        //判断用户是否登录
        if (user.getId() == 0){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).build()));
            return;
        }

        //获取游戏id
        Long gameid = Long.valueOf(request.getParameter("gameid"));
        //获取在线用户id
        Long id = user.getId();

        //根据游戏id查游戏详情
        Game game = null;
        try {
            game = gameService.getone(gameid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //加入愿望单
        int result = 0;
        try {
            result = gameService.addDream(id,game);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (result == 1){
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(0).build()));
        }else{
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).build()));
        }

    }

    //游戏详情
    private void detail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Long gameid = Long.valueOf(request.getParameter("gameid"));
        Game game = null;
        try {
            game = gameService.getone(gameid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        List<Comment> comment = null;

        try {
            comment = commentService.show(gameid);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        System.out.println(comment);
        session.setAttribute("game" , game);
        session.setAttribute("comment", comment);
        response.sendRedirect(request.getContextPath()+"/game/detail.jsp");
    }

    //查询所有游戏
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GameDto gameDto = new GameDto();
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)){
            gameDto.setName(name);
        }

        String type = request.getParameter("type");
        if (StringUtils.isNotBlank(type)){
            gameDto.setType(GameTypeEnum.valueOf(type));
        }

        String price = request.getParameter("price");
        if (StringUtils.isNotBlank(price)){
            gameDto.setPrice(Double.valueOf(price));
        }

        String topmenu = request.getParameter("topmenu");
        if (StringUtils.isNotBlank(topmenu)){
            gameDto.setTopmenu(topmenu);
        }


        //获取页码
        Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
        //每页显示的条数
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));

        gameDto.setPageNum(pageNum);
        gameDto.setPageSize(pageSize);

        //调用service获取游戏列表
        List<Game> gameList = null;
        try {
            gameList = gameService.getList(gameDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        Long count = null;
        try {
            count = gameService.getcount(gameDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        request.setAttribute("game", gameList);
        request.setAttribute("count", count);
        request.setAttribute("pageCount", (int) Math.ceil(count*1.0 / pageSize));
        request.setAttribute("type", type);
        request.setAttribute("price", price);
        request.setAttribute("topmenu", topmenu);
        request.getRequestDispatcher("/game/game.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
